Page({
    data: {
      newMobile: '',
      code: '',
      sendText: '获取验证码',
      canSend: true,
      timer: null,
      count: 60
    },
    onInputMobile(e) {
      this.setData({ newMobile: e.detail.value });
    },
    onInputCode(e) {
      this.setData({ code: e.detail.value });
    },
    sendCode() {
      if (!this.data.canSend) return;
      if (!this.data.newMobile) {
        wx.showToast({ title: '请输入手机号', icon: 'none' });
        return;
      }
      // 调用后端发送验证码接口
      wx.request({
        url: 'http://localhost:8080/sysUser/changePhone', // 你的接口
        method: 'POST',
        data: { mobile: this.data.newMobile },
        success: (res) => {
          if (res.data.code === 200) {
            wx.showToast({ title: '验证码已发送', icon: 'success' });
            this.startTimer();
          } else {
            wx.showToast({ title: res.data.message || '发送失败', icon: 'none' });
          }
        }
      });
    },
    startTimer() {
      this.setData({ canSend: false, sendText: '60s' });
      let count = 60;
      this.data.timer = setInterval(() => {
        count--;
        this.setData({ sendText: count + 's' });
        if (count <= 0) {
          clearInterval(this.data.timer);
          this.setData({ canSend: true, sendText: '获取验证码' });
        }
      }, 1000);
    },
    bindPhone() {
      if (!this.data.newMobile) {
        wx.showToast({ title: '请输入手机号', icon: 'none' });
        return;
      }
      if (!this.data.code) {
        wx.showToast({ title: '请输入验证码', icon: 'none' });
        return;
      }
      // 调用后端绑定手机接口
      const app = getApp();
      const username = app.globalData.loginUserInfo.username;
      wx.request({
        url: 'http://localhost:8080/sysUser/changePhone', // 你的接口
        method: 'POST',
        data: {
          username,
          mobile: this.data.newMobile,
          code: this.data.code
        },
        success: (res) => {
            console.log(res.data.code);
          if (res.data.code === 200) {
            app.globalData.loginUserInfo.mobile = this.data.newMobile;
            wx.setStorageSync('loginUserInfo', app.globalData.loginUserInfo);
            wx.navigateTo({ url: '/my/bindPhone3/bindPhone3' });
          } else {
            wx.showToast({ title: res.data.message || '绑定失败', icon: 'none' });
          }
        }
      });
    },
    onUnload() {
      if (this.data.timer) clearInterval(this.data.timer);
    }
  });